package net.sashag.nadlandroid;

import java.util.List;

import android.util.Log;

import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;

public class ApartmentRating {

	private int numRatings;
	private float currRating;
	private ParseObject ratingObject;
	
	public ApartmentRating(String apartmentId) {
		ParseQuery query = new ParseQuery("ApartmentRating");
		query.whereEqualTo("ApartmentId", apartmentId);
		List<ParseObject> matches = null;
		try {
			matches = query.find();
		} catch (ParseException e) {
			Log.w("ApartmentRating", "Error performing ParseQuery: " + e.getMessage());
		}
		if (matches == null || matches.size() == 0) {
			ratingObject = new ParseObject("ApartmentRating");
			ratingObject.put("ApartmentId", apartmentId);
			ratingObject.put("NumRatings",  0);
			ratingObject.put("CurrRating", 0.0);
			ParseACL acl = new ParseACL(); //Ratings can be changed by everyone
			acl.setPublicReadAccess(true);
			acl.setPublicWriteAccess(true);
			ratingObject.setACL(acl);
			ratingObject.saveEventually();
		} else {
			ratingObject = matches.get(0);
		}
		numRatings = ratingObject.getInt("NumRatings");
		currRating = (float) ratingObject.getDouble("CurrRating");
	}
	
	public void addUserRating(float rating) {
		currRating = (currRating * numRatings + rating) / (numRatings + 1);
		ratingObject.put("NumRatings", ++numRatings);
		ratingObject.put("CurrRating", currRating);
		Log.v("ApartmentRating", "New rating: " + currRating + ", votes: " + numRatings);
		ratingObject.saveEventually();
	}
	
	public float getCurrentRating() {
		return currRating;
	}

	public int getNumRatings() {
		return numRatings;
	}
	
}
